<?php
/**
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/21
 * Time: 10:27
 */

namespace app\api\model;


use app\home\model\BaseModel;
use common\Token;
use think\Exception;
use think\facade\Db;

class User extends BaseModel
{
    /**
     * 自动生成写入时间
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 登录
     * @param $where
     * @return bool|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($mobile,$password){
        $where[] = ['mobile', '=', $mobile];
        /* 获取用户数据 */
        $user = Db::name('user')->where($where)->find();
        if(!$user) {
            throw new Exception('该账户还未注册',0);
        }
        if($user['password'] != md5($password)) {
            throw new Exception('密码错误',1);
        }
        if($user['status'] != 1 ) {
            throw new Exception('账号被禁用',2);
        }
        $userData = [
            'user_id' => $user['user_id'],
            'exp' => time() + 2592000,
        ];
        $token = Token::getToken($userData);
        $updateUser = [
            'lastlogin_time' => time()
        ];
        Db::name('user')->where($where)->update($updateUser);
        $log = array(
            'user_id' => $user['user_id'],
            'login_time' => time(),
            'login_ip' => request()->ip()
        );
        Db::name('user_loginlog')->insert($log);
        return $token;
    }

    public function loginBySmCode($where){
        /* 获取用户数据 */
        $user = Db::name('user')->where($where)->find();
        if(!$user) {
            throw new Exception('该账户还未注册',0);
        }
        if($user['status'] != 1 ) {
            throw new Exception('账号被禁用',2);
        }
        $userData = [
            'user_id' => $user['user_id'],
            'exp' => time() + 2592000,
        ];
        $token = Token::getToken($userData);
        $updateUser = [
            'lastlogin_time' => time()
        ];
        Db::name('user')->where($where)->update($updateUser);
        $log = array(
            'user_id' => $user['user_id'],
            'login_time' => time(),
            'login_ip' => request()->ip()
        );
        Db::name('user_loginlog')->insert($log);
        return $token;
    }


    /**
     * 注册
     * @param $param
     * @return bool|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function doRegister($param){
        $checkUser = Db::name('user')->where('mobile',$param['mobile'])->find();
        if ($checkUser){
            throw new Exception('该手机号码已注册',0);
        }
        $p_user = Db::name('user')->where('code',$param['code'])->field('user_id,tree,lvl')->find();
        if (!$p_user){
            throw new Exception('邀请码错误',0);
        }
        $redisCode = cache('register.'.$param['mobile']);
        if ($redisCode != $param['sm_code']) {
            throw new Exception('验证码错误',0);
        }
        $data = [
            'code' => $this->getCode(mt_rand(100000,999999)),
            'pid' => $p_user['user_id'],
            'lvl' => $p_user['lvl'] + 1,
            'tree' => $p_user['tree'].','.$p_user['user_id'],
            'mobile' => $param['mobile'],
            'username' => substr_replace($param['mobile'],'****',3,4),
            'password' => md5($param['password']),
            'photo' => '/static/api/default.png',
            'create_time' => time(),
            'lastlogin_time' => time()
        ];
        $user_id = Db::name('user')->insertGetId($data);
        $userData = [
            'user_id' => $user_id,
            'exp' => time() + 2592000,
        ];
        $token = Token::getToken($userData);
        $log = array(
            'user_id' => $user_id,
            'login_time' => time(),
            'login_ip' => request()->ip()
        );
        cache('register.'.$param['mobile'],NULL);
        Db::name('user_loginlog')->insert($log);
        return $token;
    }


    /**
     * 修改密码
     * @param $param
     * @throws Exception
     * @throws \think\db\exception\DbException
     */
    public function updatePwd($param){
        $smCode = cache('forget.'.$param['mobile']);
        if ($smCode != $param['sm_code']) {
            throw new Exception('验证码错误',0);
        }
        $where = ['mobile' => $param['mobile']];
        $data = ['password' => md5($param['password'])];
        $res = Db::name('user')->where($where)->update($data);
        if (!$res){
            throw new Exception('操作失败',0);
        }
        cache('forget.'.$param['mobile'],NULL);
    }

    /**
     * 获取不重复的推荐码
     * @param $code
     * @return int
     */
    public function getCode($code)
    {
        if (Db::name('user')->where(array('code' => $code))->value('user_id')) {
            $code = mt_rand(100000,999999);
            return $code;
        } else {
            return $code;
        }
    }

    public function getNumber($number)
    {
        $user = $this->where("number", $number)->find();
        return $user;
    }


    public function getUnionid($unionid)
    {
        $user = $this->where("unionid", $unionid)->find();
        return $user;
    }

    public function getOpenid($openid)
    {
        $user = $this->where("openid", $openid)->find();
        return $user;
    }
}